﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using FileManager_Client.BusinessLogic;
using FileManager_Client.BusinessLogic.FileManagerUserService;
using FileManager_Client.Utility;

namespace FileManager_Client.PresentationLayer
{
    public partial class ReNameFile : Form
    {
        private UserLoginResult userSession;
        private List<string> _hasFileNameCollection;
        private string _fileSid;
        private string _fileOldName;
        private ToolTip _fileNameToolTip = new ToolTip();
        private FileService fileService;
        private WaitDialogForm _waitBeforeLogin;
        private string _folderId;
        private ServerFiles _serverFiles;
        private static object lockWait = new object();
        public ReNameFile(List<string> hasFileNameCollection, string fileSid, string fileOldName, string folderId, ServerFiles serverFiles)
        {
            InitializeComponent();
            _hasFileNameCollection = hasFileNameCollection;
            _fileSid = fileSid;
            _fileOldName = fileOldName;
            userSession = CacheGlobal.GetCache(GlobalString.System_Config_String.UserSession) as UserLoginResult;
            tb_FileName.TextChanged += tb_FileName_TextChanged;
            _fileNameToolTip.AutoPopDelay = 5000;
            _fileNameToolTip.InitialDelay = 1000;
            _fileNameToolTip.ReshowDelay = 500;
            _fileNameToolTip.ShowAlways = true;
            _fileNameToolTip.IsBalloon = true;
            _fileNameToolTip.ToolTipIcon = ToolTipIcon.Error;
            _fileNameToolTip.Active = true;
            _fileNameToolTip.ToolTipTitle = "输入提示:";
            fileService = new FileService();
            _folderId = folderId;
            _serverFiles = serverFiles;
            tb_FileName.Text = fileOldName;
        }

        void tb_FileName_TextChanged(object sender, EventArgs e)
        {
            _fileNameToolTip.Hide(tb_FileName);
        }

        private void tb_FileName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13) return;
            if(CheckFileName())
                FileReName();
        }

        private void btn_Confrim_Click(object sender, EventArgs e)
        {
            if(CheckFileName())
                FileReName();
        }

        private bool CheckFileName()
        {
            var fileName = tb_FileName.Text;
            if(fileName.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)
            {
                _fileNameToolTip.Show(string.Empty,tb_FileName,0);
                _fileNameToolTip.Show("文件名不能包含\\/:*?\"<>| 特殊字符!", tb_FileName, 0);
                return false;
            }
            if(string.IsNullOrEmpty(fileName.Trim())||fileName.Substring(fileName.LastIndexOf('.')).Equals(fileName))
            {
                _fileNameToolTip.Show(string.Empty,tb_FileName,0);
                _fileNameToolTip.Show("文件名不能为空!", tb_FileName, 0);
                return false;
            }
            if(_fileOldName.Equals(fileName))
            {
                _fileNameToolTip.Show(string.Empty,tb_FileName,0);
                _fileNameToolTip.Show("文件名没有发生变化!", tb_FileName, 0);
                return false;
            }
            if(_hasFileNameCollection.Contains(fileName))
            {
                _fileNameToolTip.Show(string.Empty,tb_FileName,0);
                _fileNameToolTip.Show("该文件夹中已经包含了这个文件名!", tb_FileName, 0);
                return false;
            }
            return true;
        }

        private void FileReName()
        {
            try
            {
                lock (lockWait)
                {
                    _waitBeforeLogin = new WaitDialogForm(GlobalString.System_Config_String.FileReNameStr,
                                                          GlobalString.System_Config_String.MbxInfoStr)
                    {
                        BackColor = BackColor
                    };
                    _waitBeforeLogin.Hide();
                }
                var backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork += backgroundWorker_DoWork;
                var fileReNameArgs = new FileReNameArgs
                                         {
                                             FileNewNamek__BackingField = tb_FileName.Text,
                                             FileSidk__BackingField = _fileSid,
                                             UserIdk__BackingField = userSession.UserIdk__BackingField
                                         };
                backgroundWorker.RunWorkerAsync(fileReNameArgs);
                _waitBeforeLogin.ShowDialog();
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("FileReName has problem", ex);
                XtraMessageBox.Show("修改文件名失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
            }
        }

        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var fileArgs = e.Argument as FileReNameArgs;
                var reslut =  fileService.ChangeFileName(fileArgs);
                Invoke((EventHandler)delegate
                {
                    _waitBeforeLogin.Close();
                });
                if (reslut.Resultk__BackingField)
                {
                    XtraMessageBox.Show("修改文件名成功!", GlobalString.System_Config_String.MbxInfoStr,
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    _serverFiles.Invoke((EventHandler)delegate
                    {
                        _serverFiles.UpdateListView(_folderId);
                    });
                    Invoke((EventHandler)delegate
                    {
                        Close();
                    });
                }
                else
                {
                    var message = string.Empty;
                    switch (reslut.ResultExceptionk__BackingField)
                    {
                            case BaseExceptionEnum.NotFindFileException:
                            message = GlobalString.System_Exception_String.NotFindFileExceptionStr;
                            break;
                            case BaseExceptionEnum.FileReNameException:
                            message = GlobalString.System_Exception_String.FileReNameExceptionStr;
                            break;
                    }
                    XtraMessageBox.Show(message, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("FileReName backgroundWorker_DoWork has problem", ex);
                XtraMessageBox.Show("修改文件名失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                Invoke((EventHandler)delegate
                {
                    Close();
                });
            }
        }
    }
}
